package com.zlk.algorithm.huawei.leetcode.hash;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: algorithm
 * @ClassName TwoSum_01
 * @description:
 * @author: slfang
 * @create: 2024-12-31 13:23
 * @Version 1.0
 **/
public class Code01_TwoSum {

    @Test
    public void test(){
        int[] nums = new int[]{-1,-2,-3,-4,-5};
        twoSum(nums,-8);
    }

    public int[] twoSum3(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

    public int[] twoSum2(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    public int[] twoSum(int[] nums, int target) {
        int[] rest = new int[nums.length];
        for (int i = 0,cur; i < nums.length; i++) {
            cur = nums[i];
            rest[i]=target-cur;
        }
        int[] ans = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int cur = nums[i];
            for (int j = 0; j < nums.length; j++) {
                if(i==j){
                    continue;
                }
                if(cur==rest[j]){
                    ans[0]=i;
                    ans[1]=j;
                    break;
                }
            }
        }
        return ans;
    }



}
